package proto

import (
	"bufio"
	"cli-desktop/public"
	"io"
	"strconv"
)

/*
*  -*- coding:utf8 -*-
*
*
*
*  @Author  : chengms
*  @WebSite : chengms.com
*  @Email   : chengms2012@163.com
*  @TIME    : 2020/8/18 下午8:27
*  @File    : reader.go
 */

type CommandReader struct {
	reader *bufio.Reader
}

func NewCommandReader(reader io.Reader) *CommandReader {
	return &CommandReader{
		reader: bufio.NewReader(reader),
	}
}

//
func (r *CommandReader) Read() (cmdBuf CommandBuf, err error) {
	lenBuf := make([]byte, 8) // 读取包长度字符串
	_, err = r.reader.Read(lenBuf)
	if err != nil {
		err = CloseTcpErr
		return
	}

	// 将 16 进制数字 的字符串转换为十进制数字 ，example： ”00400“  -> 0x400  -> 1024
	bufLen, err := strconv.ParseInt(string(lenBuf), 16, 32)
	if err != nil {
		public.Loggerf.Errorf("Trans length err:%v", err)
		err = InvalidMessageErr
		return
	}
	// public.Loggerf.Debugf("RevcLength: %v", bufLen)

	line := make([]byte, bufLen)
	_, err = r.reader.Read(line)
	if err != nil {
		err = CloseTcpErr
		return
	}

	msg := string(line)
	// public.Loggerf.Debugf("Revc: %v", msg)

	if msg[bufLen-2:bufLen-1] != ProtocolSep {
		err = InvalidMessageErr
		return
	}

	err = public.Jsonit.UnmarshalFromString(string(msg[:bufLen-2]), &cmdBuf)
	if err != nil {
		public.Loggerf.Errorf("Decode msg err: %v", err)
		return
	}

	if cmdBuf.Protocol != ProtocolName || cmdBuf.Vserion != ProtocolVersion {
		err = InvalidMessageErr
		public.Loggerf.Errorf("Buffer: %v", cmdBuf)
		return
	}

	return
}
